"""
自动化操作工具类
"""

import time
from turtle import st
import pyautogui
import pyperclip
from typing import Optional, Tuple


class AutomationUtils:
    """自动化操作工具类"""
    
    def __init__(self, wait_time: float = 1.0):
        """
        初始化自动化工具
        
        Args:
            wait_time: 默认等待时间
        """
        self.wait_time = wait_time
        
        # 设置pyautogui参数
        pyautogui.FAILSAFE = True  # 启用故障保护
        pyautogui.PAUSE = 0.1  # 设置操作间隔
    
    def calculate_click_position(self, location: Tuple[int, int, int, int], 
                               offset_x: int = 25, offset_y: int = 25) -> Tuple[int, int]:
        """
        计算点击位置
        
        Args:
            location: 图像位置
            offset_x: X轴偏移
            offset_y: Y轴偏移
            
        Returns:
            点击坐标 (x, y)
        """
        x, y = location[0], location[1]
        pos_x = x // 2 + offset_x
        pos_y = y // 2 + offset_y
        return pos_x, pos_y
    
    def click_at_location(self, location: Tuple[int, int, int, int], offset_x: int = 25, 
                         offset_y: int = 25, button: str = 'left', 
                         duration: float = 1.0) -> bool:
        """
        在指定位置点击
        
        Args:
            location: 图像位置
            offset_x: X轴偏移
            offset_y: Y轴偏移
            button: 鼠标按钮 ('left', 'right', 'middle')
            duration: 持续时间
            
        Returns:
            是否成功
        """
        try:
            pos_x, pos_y = self.calculate_click_position(location, offset_x, offset_y)
            print(f"点击位置: ({pos_x}, {pos_y})")
            
            pyautogui.moveTo(pos_x, pos_y, duration=0.2)
            time.sleep(0.1)
            # pyautogui.click(button=button, duration=duration)
            pyautogui.leftClick()
            time.sleep(self.wait_time)
            return True
        except Exception as e:
            print(f"点击操作失败: {e}")
            return False
    
    def type_text(self, text: str, clear_first: bool = True) -> bool:
        """
        输入文本
        
        Args:
            text: 要输入的文本
            clear_first: 是否先清空
            
        Returns:
            是否成功
        """
        try:
            if clear_first:
                print(f"清空文本")
                pyautogui.hotkey('command', 'a')
                time.sleep(0.5)
                pyautogui.press('backspace')
                time.sleep(0.5)
            
            pyperclip.copy(text)
            time.sleep(0.5)
            pyautogui.hotkey('command', 'v')
            time.sleep(self.wait_time)
            
            # pyautogui.write(text)
            # time.sleep(1)
            # pyautogui.press('enter')
            # time.sleep(3)
            
            return True
        except Exception as e:
            print(f"输入文本失败: {e}")
            return False
    
    def press_key(self, key: str, times: int = 1) -> bool:
        """
        按键操作
        
        Args:
            key: 按键名称
            times: 按键次数
            
        Returns:
            是否成功
        """
        try:
            for _ in range(times):
                pyautogui.press(key)
                time.sleep(0.1)
            time.sleep(self.wait_time)
            return True
        except Exception as e:
            print(f"按键操作失败: {e}")
            return False
    
    def hotkey(self, *keys) -> bool:
        """
        组合键操作
        
        Args:
            *keys: 按键序列
            
        Returns:
            是否成功
        """
        try:
            pyautogui.hotkey(*keys)
            time.sleep(self.wait_time)
            return True
        except Exception as e:
            print(f"组合键操作失败: {e}")
            return False
    
    def scroll(self, clicks: int, direction: str = 'down') -> bool:
        """
        滚动操作
        
        Args:
            clicks: 滚动次数
            direction: 滚动方向 ('up', 'down')
            
        Returns:
            是否成功
        """
        try:
            if direction == 'up':
                pyautogui.scroll(clicks)
            else:
                pyautogui.scroll(-clicks)
            time.sleep(self.wait_time)
            return True
        except Exception as e:
            print(f"滚动操作失败: {e}")
            return False
    
    def move_mouse(self, x: int, y: int, duration: float = 0.5) -> bool:
        """
        移动鼠标
        
        Args:
            x: X坐标
            y: Y坐标
            duration: 移动持续时间
            
        Returns:
            是否成功
        """
        try:
            pyautogui.moveTo(x, y, duration=duration)
            # time.sleep(self.wait_time)
            return True
        except Exception as e:
            print(f"移动鼠标失败: {e}")
            return False
    
    def wait_for_image(self, image_path: str, timeout: int = 10, 
                      confidence: float = 0.8) -> Optional[Tuple[int, int, int, int]]:
        """
        等待图像出现
        
        Args:
            image_path: 图像文件路径
            timeout: 超时时间（秒）
            confidence: 置信度
            
        Returns:
            图像位置或None
        """
        start_time = time.time()
        while time.time() - start_time < timeout:
            try:
                location = pyautogui.locateOnScreen(image_path, confidence=confidence)
                if location:
                    return location
            except pyautogui.ImageNotFoundException:
                pass
            time.sleep(0.5)
        
        return None

    def click(self, key: str, duration: int = 1) -> bool:
        """
        按键操作
        
        Args:
            key: 按键名称
            duration: 持续时间
            
        Returns:
            是否成功
        """
        try:
            pyautogui.click(button=key, duration=duration)
            return True
        except Exception as e:
            print(f"按键操作失败: {e}")
            return False

    
    def copy_paste(self, text: str) -> bool:
        """
        复制粘贴文本
        
        Args:
            text: 要复制的文本
            
        Returns:
            是否成功
        """
        try:
            # print(f"复制粘贴文本: {text}")
            pyperclip.copy(text)

            time.sleep(1)

            pyautogui.hotkey('command', 'v')

            time.sleep(1)
            
            return True
        except Exception as e:
            print(f"复制粘贴文本: {e}")
            return False
